{% extends "base.html" %}


{% block content %}


{% for c in commands %}
 <button type=button class="bigbutton" command="{{c}}">{{c}}</button>
{% end %}


<div class=info>
  <b>
  <pre id="status">
    {{status}}
  </pre>
  </b>
</div>

<div class=info>
  <pre id="log">
  </pre>
</div>


<script>
$(function() {
    console.log("task setup");
    function ShowResult(data, status) {
        //console.log("command completed [" + status + "]");
        //console.log("command completed [" + data + "]");
        $("#status").html(data);
    }

    function ClearLog() {
        console.log("clear log");
        $("#log").html("");
    }

    function AppendToLog(data) {
        // do some extra work to interpret carriage returns (cr)
        // correctly. This helps with progress reports
        var cr = data.lastIndexOf("\r");
        //console.log("length " + data.length +  " " + cr);
        if (cr >= 0) {
           data = data.slice(cr + 1);

           var old_data = $("#log").text();
           var nl = old_data.lastIndexOf("\n");
           if (nl < 0) {
               old_data = "";
           } else {
               old_data = old_data.slice(0, nl + 1)
           }
           $("#log").html(old_data + data);
        } else {
          $("#log").append(data);
       }
    }

    function SendCommand(command) {
        console.log("send command " + command);
        $.get("/task_command", {command: command}, ShowResult);
    }

    function ButtonClick() {
        var command = $(this).attr("command");
        // hack
        if (command != "kill") {
            ClearLog();
        }
        SendCommand(command);
    }

    $("button").click(ButtonClick);


    var ws = new WebSocket("ws://" + location.host +  "/task_websocket/");
    ws.onopen = function() {};
    ws.onmessage = function(event) { AppendToLog(event.data); };

 });

 </script>

{% end %}
